package com.tian.hello.customerview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View

/**
 * Description:
 * <br></br>Author:  tianjinyong
 * <br></br>Date:    2020/7/21 3:32 PM
 */
class CircleView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    init {
        init()
    }

    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)


    private fun init() {
        val mColor = Color.RED
        mPaint.color = mColor
    }

    override fun onDraw(canvas: Canvas) {
        // 不支持view的padding
//        int width = getWidth();
//        int height = getHeight();
//        int radius = Math.min(width, height) / 2;
//        canvas.drawCircle(width / 2, height / 2, radius, mPaint);


        // 自定义view 考虑padding
        val paddingLeft = paddingLeft
        val paddingRight = paddingRight
        val paddingTop = paddingTop
        val paddingBottom = paddingBottom
        val width = width - paddingLeft - paddingRight
        val height = height - paddingBottom - paddingTop
        val radius = Math.min(width, height) / 2
        canvas.drawCircle((paddingLeft + width / 2).toFloat(), (paddingTop + height / 2).toFloat(), radius.toFloat(), mPaint)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        // 自定义view 如果不重写这个方法没，会造成在xml中使用wrap_content达不到预期效果
        val widthSpecMode = MeasureSpec.getMode(widthMeasureSpec)
        var widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightSpecMode = MeasureSpec.getMode(heightMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (widthSpecMode == MeasureSpec.AT_MOST) {
            widthSize = 200
        }
        if (heightSpecMode == MeasureSpec.AT_MOST) {
            heightSize = 200
        }
        setMeasuredDimension(widthSize, heightSize)
    }
}